<?php

namespace app\beautiful\controller\admin\appointment;

use app\BaseController;
use app\beautiful\model\appointment\PositionModel;
use app\beautiful\model\appointment\TechnicianModel;

class Position extends BaseController
{
    protected $name = '岗位';

    public function index()
    {
        $position_model = new PositionModel();
        $where = [
            ['shop_id', '=', $this->request->shopId],
        ];
        $name = $this->request->param('name/s');
        if (!empty($name)){
            $where[] = ['name', 'like', '%'.$name.'%'];
        }
        $is_show = $this->request->param('is_show');

        if ($is_show!=''){
            $where[] = ['is_show', '=', $is_show];
        }
        $list = $position_model->where($where)->select();
        return $this->success($list);
    }

    public function save()
    {
        $position_id = $this->request->param('position_id/d', 0);
        $name = $this->request->param('name/s');
        $is_show = $this->request->param('is_show/d', 0);
        if (empty($name)) return $this->error('请输入岗位名称');

        $position_model = PositionModel::where([
            ['shop_id', '=', $this->request->shopId],
            ['name', '=', $name],
        ])->find();
        if ($position_id != 0) {
            if (null !== $position_model && $position_model->position_id!=$position_id){
                return $this->error('岗位已存在');
            }
            $position_model = PositionModel::where([
                ['position_id', '=', $position_id],
            ])->find();

            if (null == $position_model){
                return $this->error('修改的岗位不存在');
            }
        } else {
            if (null !== $position_model) {
                return $this->error('岗位已存在');
            }
            $position_model = new PositionModel();
        }
        $position_model->name = $name;
        $position_model->shop_id = $this->request->shopId;
        $position_model->is_show = $is_show;
        $position_model->save();
        return $this->success(['id'=>$position_model->position_id]);

    }

    public function del(){
        $position_id = $this->request->param('position_id/d');
        if (empty($position_id)) return $this->error('请输入岗位id');
        $position_model = PositionModel::find($position_id);
        if (null == $position_model){
            return $this->error('岗位不存在');
        }

        $technician = TechnicianModel::where([
            ['position_id','=',$position_id]
        ])->find();
        if (null !== $technician) {
            return $this->error('该岗位存在员工，无法删除');
        }
        $position_model->delete();

        return $this->success([]);

    }

}
